<?php

namespace app\stock\controller\business;

use think\Controller;

class Highsea extends Controller
{
  public function _initialize()
  {
    parent::_initialize();
    $this->BusinessModel = model('Business.Business');
    $this->AdminModel = model('Admin');
    $this->ReceiveModel = model('Business.Receive');
  }

  // 列表
  public function index()
  {
    $data = $this->BusinessModel->with('source')->where('adminid', null)->order('createtime DESC')->select();

    $this->success('', '', $data);
  }

  // 详情
  public function info()
  {
    $busid = $this->request->param('busid', 0, 'trim');

    $businessinfo = $this->BusinessModel->field('id,nickname,gender,deal,createtime')->with('source')->find($busid);

    if (!$businessinfo) {
      $this->success('当前用户不存在');
    }

    $this->success('', '', $businessinfo);
  }

  // 管理员列表
  public function admin()
  {
    $data = $this->AdminModel->field('id,username')->order('createtime DESC')->select();

    $this->success('', '', $data);
  }


  // 分配 和 申请 
  public function allot()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $adminid = $this->request->param('adminid', 0, 'trim');
    $status = $this->request->param('status', '', 'trim');

    $businessinfo = $this->BusinessModel->find($busid);

    if (!$businessinfo) {
      $this->error('当前用户不存在');
    }

    $admininfo = $this->AdminModel->find($adminid);

    if (!$admininfo) {
      $this->error('分配人员不存在');
    }

    // 开始事务
    $this->BusinessModel->startTrans();
    $this->ReceiveModel->startTrans();

    $businessStatus = $this->BusinessModel->where('id', $busid)->update(['adminid' => $adminid]);

    if ($businessStatus == false) {
      $this->error($this->BusinessModel->geError());
    }

    $ReceiveData = [
      'applyid' => $adminid,
      'status' => $status,
      'busid' => $busid
    ];

    // 校验器
    $receiveStatus = $this->ReceiveModel->save($ReceiveData);
    if ($receiveStatus == false) {
      $this->BusinessModel->rollback();
      $this->error($this->ReceiveModel->geError());
    }

    if ($receiveStatus == false || $businessStatus == false) {
      $this->BusinessModel->rollback();
      $this->ReceiveModel->rollback();
      $this->error('操作失败');
    } else {
      $this->BusinessModel->commit();
      $this->ReceiveModel->commit();
      $this->success('操作成功');
    }
  }

  // 删除
  public function del()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $adminid = $this->request->param('adminid', 0, 'trim');

    $businessinfo = $this->BusinessModel->find($busid);

    if (!$businessinfo) {
      $this->error('当前用户不存在');
    }

    $admininfo = $this->AdminModel->find($adminid);

    if (!$admininfo) {
      $this->error('管理员不存在');
    }

    $result = $this->BusinessModel->destroy($busid);

    if ($result === false) {
      $this->error('删除失败');
    } else {
      $this->success('删除成功');
    }
  }
}
